<?php
/**
 * Created by PhpStorm.
 * User: jungshen
 * Date: 2018/8/6
 * Time: 15:20
 */

namespace app\api\controller\supplier;

use Db;
use app\api\controller\BasicUserApi;
use think\Exception;

class Goods extends BasicUserApi
{
    /**
     * 添加产品
     * @return \think\response\Json
     */
    public function add(){
        try{
            $post=$this->request->only(['name','sku','price','material','image','sort','desc'],'post');

            $validate=new \app\api\validate\Goods();
            if(!$validate->check($post)){
                return json(['msg'=>$validate->getError()],403);
            }
            $post['status']=0;
            $post['mid']=UID;
            Db::name('supplier_goods')->cache('self_goods_list')->insert($post);
            return json(['msg'=>'添加成功']);
        }catch(\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 修改产品
     * @return \think\response\Json
     */
    public function edit(){
        try{
            $post=$this->request->only(['id','name','sku','material','price','image','sort','desc'],'post');

            $validate=new \app\api\validate\Goods();
            if(!$validate->scene('edit')->check($post)){
                return json(['msg'=>$validate->getError()],403);
            }
            $post['status']=0;
            //TODO::待确认是否需要重置主键
            Db::name('supplier_goods')->cache('self_goods_list')->update($post);
            return json(['msg'=>'修改成功']);
        }catch(\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 获取产品列表
     * @return \think\response\Json
     */
    public function index()
    {
        try{
            $list=Db::name('supplier_goods')->where('mid',UID)->cache('self_goods_list',60)->order('sort')->select();
            return json(['msg'=>'success','data'=>$list]);
        }catch (\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 获取产品详细信息
     * @return \think\response\Json
     */
    public function info()
    {
        try{
            $id=input('id');
            $goods=Db::name('supplier_goods')->where('id',$id)->hidden('mid,status,sort')->find();
            return json(['msg'=>'success','data'=>$goods]);
        }catch (Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }
    /**
     * 删除产品
     * @return \think\response\Json
     */
    public function del()
    {
        try{
            $id=input('id');
            Db::name('supplier_goods')->where('mid',UID)->cache('self_goods_list')->where('id',$id)->delete();
            return json(['msg'=>'删除成功']);
        }catch(\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }
}